package com.qianya.system.manage.web.login.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianya.model.common.JWTUtil;
import com.qianya.model.pojo.login.qo.LoginUsersInsertQO;
import com.qianya.model.pojo.login.qo.LoginUsersQO;
import com.qianya.model.pojo.login.qo.LoginUsersupdateByIdQO;
import com.qianya.model.pojo.login.qo.LoginUsersupdateQO;
import com.qianya.model.pojo.login.vo.LoginRoleUserVO;
import com.qianya.model.pojo.login.vo.LoginRoleVO;
import com.qianya.model.pojo.login.vo.LoginUsersVO;
import com.qianya.system.manage.util.password.PasswordUtil;
import com.qianya.system.manage.web.login.mapper.CustomMapper;
import com.qianya.system.manage.web.login.model.LoginDept;
import com.qianya.system.manage.web.login.model.LoginUsers;
import com.qianya.system.manage.web.login.service.ILoginUsersService;
import com.qianya.system.manage.web.login.mapper.LoginUsersMapper;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.qianya.model.common.CommonResult;
import com.qianya.model.common.ResultCode;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户服务实现类
 * </p>
 *
 * @author wy
 * @since 2020-07-02
 */
@Service
@Transactional
public class LoginUsersServiceImpl extends ServiceImpl<LoginUsersMapper, LoginUsers> implements ILoginUsersService {

    @Resource
    private LoginUsersMapper loginUsersMapper;

    @Resource
    private CustomMapper customMapper;
    @Resource
    HttpServletRequest request;

    /**
     * 查找 用户
     *
     * @author wy
     * @since 2020-07-02
     */
    @Override
    public CommonResult find(LoginUsersQO loginUsersQO) {

        List<LoginUsersVO> loginUsersVOList = loginUsersMapper.find(loginUsersQO);

        return CommonResult.success(loginUsersVOList);
    }

    /**
     * 新增 用户
     *
     * @author wy
     * @since 2020-07-02
     */
    @Transactional
    @Override
    public CommonResult create(LoginUsersInsertQO loginUsersInsertQO) {

        //拿到request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //new一个loginUsers对象
        LoginUsers loginUsers = new LoginUsers();

        //将loginUsersInsertQO的属性赋值到loginUsers

        BeanUtils.copyProperties(loginUsersInsertQO, loginUsers);

        //拿到创建人id
        String userId = JWTUtil.getUserId(request.getHeader("token"));
        //写入创建人id
        loginUsers.setUCreateId(userId);
        //写入日期
        loginUsers.setUCreateTime(new Date());
        //生成用户ID
        String uuid = IdUtil.simpleUUID();
        //写入用户ID
        loginUsers.setUId(uuid);

        //写入用户加入密码
        loginUsers.setUPassword(PasswordUtil.encodePassword(loginUsers.getUPassword()));

//        LoginUsersVO loginUsersVO = loginUsersMapper.findByPhone(loginUsers.getUPhone());
        LoginUsers u_username = getOne(new QueryWrapper<LoginUsers>().eq("U_USERNAME", loginUsers.getUUsername()));
        if (u_username != null) {
            return CommonResult.error(ResultCode.ERROR, "用户名已存在,请重新输入");
        }

        LoginUsers u_phone = getOne(new QueryWrapper<LoginUsers>().eq("U_PHONE", loginUsers.getUPhone()));
        if (u_phone != null) {
            return CommonResult.error(ResultCode.ERROR, "手机号已存在,请重新输入");
        }

        //插入部门用户关联
        String[] deptIds = loginUsersInsertQO.getDeptId().split(",");
        for (String deptId : deptIds) {
            customMapper.saveUserDept(uuid, deptId);
        }
        //插入角色用户关联
        String[] roleIds = loginUsersInsertQO.getRoleId().split(",");
        for (String roleId : roleIds) {
            customMapper.saveUserRole(uuid, roleId);
        }
        //插入用户表
        boolean b = save(loginUsers);
        if (b) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.error(ResultCode.ERROR, "添加失败");
    }

    /**
     * 修改 用户
     *
     * @author wy
     * @since 2020-07-02
     */
    @Override
    public CommonResult renewal(LoginUsersupdateQO loginUsersupdateQO) {
        if (loginUsersupdateQO.getUPhone() != null) {

            boolean matches = loginUsersupdateQO.getUPhone().matches("0?(13|14|15|17|18|19)[0-9]{9}");
            if (matches==false) {
                return CommonResult.error(ResultCode.ERROR, "手机号格式不对");
            }
        }
        //拿到request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //new一个loginUsers对象
        LoginUsers loginUsers = new LoginUsers();
        //将loginUsersInsertQO的属性赋值到loginUsers
        BeanUtils.copyProperties(loginUsersupdateQO, loginUsers);
        LoginUsers phone = this.getOne(new QueryWrapper<LoginUsers>()
                .eq("U_PHONE", loginUsers.getUPhone()).ne("U_ID", loginUsers.getUId()));
        if (phone != null) {
            return CommonResult.error(ResultCode.ERROR, "手机号已存在,请重新输入");
        }
        //拿到loginUsers的用户id
        String uuId = loginUsers.getUId();
        //拿到并设置修改人id
        loginUsers.setUUpdateId(JWTUtil.getUserId(request.getHeader("token")));
        //设置修改时间为系统当前时间
        loginUsers.setUUpdateTime(new Date());
        //设置修改密码(修改)
        String uPassword = loginUsers.getUPassword();
        if (StringUtils.isNotBlank(uPassword)) {
            loginUsers.setUPassword(PasswordUtil.encodePassword(loginUsers.getUPassword()));
        }
        //删除用户部门中间表信息
        customMapper.deleteUserDept(uuId);
        //删除用户角色中间表信息
        customMapper.deleteUserRole(uuId);
        //取出参数中的部门信息并以逗号切割成数组
        String[] deptIds = loginUsersupdateQO.getDeptId().split(",");
        //遍历数组
        for (String deptId : deptIds) {
            //存入部门中间表，参数为用户id和部门id
            customMapper.saveUserDept(uuId, deptId);
        }
        //同上
        String[] roleIds = loginUsersupdateQO.getRoleId().split(",");
        for (String roleId : roleIds) {
            customMapper.saveUserRole(uuId, roleId);
        }
        //修改用户信息
//        boolean b = updateById(loginUsers);
        int i = loginUsersMapper.updateById(loginUsers);


        if (i == 1) {
            return CommonResult.success("修改成功");
        }
        return CommonResult.error(ResultCode.ERROR, "修改失败");
    }

    /**
     * 删除用户
     *
     * @author wy
     * @since 2020-07-02
     */
    @Override
    public CommonResult delete(LoginUsersInsertQO loginUsersInsertQO) {
        //new一个loginUsers对象
        LoginUsers loginUsers = new LoginUsers();
        //将loginUsersInsertQO的属性赋值到loginUsers
        BeanUtils.copyProperties(loginUsersInsertQO, loginUsers);
        //拿到参数中的用户id
        String uuId = loginUsers.getUId();
        //删除用户部门中间表信息
        customMapper.deleteUserDept(uuId);
        //删除用户部门中间表信息
        customMapper.deleteUserRole(uuId);
        //删除用户信息
        boolean b = removeById(uuId);
        if (b) {
            return CommonResult.success("删除成功");
        } else {
            return CommonResult.error(ResultCode.ERROR, "删除失败");
        }
    }

    @Override
    public LoginUsersVO login(LoginUsersQO loginUsersQO) {
        return loginUsersMapper.login(loginUsersQO);
    }

    @Override
    public LoginUsersVO findById(String uId) {
        return loginUsersMapper.findById(uId);
    }


    @Override
    public CommonResult deleteById(String uId) {
        //根据id拿到LoginUsers对象
        LoginUsers loginUsers = loginUsersMapper.selectById(uId);

        Integer uStatus = loginUsers.getUStatus();

        if (uStatus == 0 || uStatus == 1) {

            //设置loginUser中的状态为2（逻辑删除）
            loginUsers.setUStatus(2);
            //删除用户部门中间表信息
            customMapper.deleteUserDept(uId);
            //删除用户部门中间表信息
            customMapper.deleteUserRole(uId);
            //保存 并判断是否保存成功
            boolean b = updateById(loginUsers);
            if (b) {
                return CommonResult.success("删除成功");
            } else {
                return CommonResult.error(ResultCode.ERROR, "删除失败");
            }
        } else {

            return CommonResult.error(ResultCode.ERROR, "请选择正确的用户进行删除");
        }

    }

    @Override
    public LoginUsersVO findByPhone(String phone) {
        return loginUsersMapper.findByPhone(phone);
    }

    @Override
    public CommonResult frozenById(String uId) {
        //根据id拿到LoginUsers对象
        LoginUsers loginUsers = loginUsersMapper.selectById(uId);
        Integer uStatus = loginUsers.getUStatus();
        if (uStatus == 1) {
            //设置loginUser中的状态为0(恢复正常)
            loginUsers.setUStatus(0);
//            //删除用户部门中间表信息
//            customMapper.deleteUserDept(uId);
//            //删除用户部门中间表信息
//            customMapper.deleteUserRole(uId);
//            //保存 并判断是否保存成功
            boolean b = updateById(loginUsers);
            if (b) {
                return CommonResult.success("解冻成功");
            } else {
                return CommonResult.error(ResultCode.ERROR, "解冻失败");
            }
        } else if (uStatus == 0) {
            loginUsers.setUStatus(1);
            boolean b = updateById(loginUsers);
            if (b) {
                return CommonResult.success("解冻成功");
            } else {
                return CommonResult.error(ResultCode.ERROR, "解冻失败");
            }
        } else {
            return CommonResult.error(ResultCode.ERROR, "请选择正确的用户进行冻结或者解冻");
        }
    }

    @Override
    public CommonResult updateUserByid(LoginUsersupdateByIdQO loginUsersupdateByIdQO) {

        if (loginUsersupdateByIdQO.getUPhone() != null) {

            boolean matches = loginUsersupdateByIdQO.getUPhone().matches("0?(13|14|15|17|18|19)[0-9]{9}");
            if (matches==false) {
                return CommonResult.error(ResultCode.ERROR, "手机号格式不对");
            }
        }

        //new一个loginUsers对象
        LoginUsers loginUsers = new LoginUsers();

        //将loginUsersInsertQO的属性赋值到loginUsers
        BeanUtils.copyProperties(loginUsersupdateByIdQO, loginUsers);


        LoginUsers phone = getOne(new QueryWrapper<LoginUsers>()
                .eq("U_PHONE", loginUsers.getUPhone()).ne("U_ID", loginUsers.getUId()));

        if (phone != null) {

            return CommonResult.error(ResultCode.ERROR, "手机号已存在,请重新输入");
        }


        //得到原密码
        String uPassword = loginUsers.getUPassword();

        //如果要修改密码
        if (uPassword !=null ) {
            String s = PasswordUtil.encodePassword(uPassword);
            //得到用户id
            String uId = loginUsers.getUId();

            //查询是否有这个用户
            LoginUsers users = loginUsersMapper.findByPassword(s, uId);

            //如果该用户不为空
            if (users != null) {
                //拿到确认密码
                String uuPassword = loginUsersupdateByIdQO.getUuPassword();
                //得到新密码
                String newPassword = loginUsersupdateByIdQO.getNewPassword();
                if (newPassword ==null && uuPassword ==null) {
                    return CommonResult.error(ResultCode.ERROR,"新密码不能为空");
                }
                if (!newPassword.equals(uuPassword)) {
                    return CommonResult.error(ResultCode.ERROR,"前后密码不一致");
                }

                //加密新密码
                loginUsers.setUPassword(PasswordUtil.encodePassword(newPassword));
                int i = loginUsersMapper.updateById(loginUsers);
                if (i == 1) {
                    return CommonResult.success("修改成功");
                }
                return CommonResult.error(ResultCode.ERROR,"修改失败");
            }
           return CommonResult.error(ResultCode.ERROR,"你输入的原密码不正确");
        }

            //如果不修改密码
            int i = loginUsersMapper.updateById(loginUsers);
            if (i == 1) {
                return CommonResult.success("修改成功");
            }
            return CommonResult.error(ResultCode.ERROR,"修改失败");

    }

    @Override
    public CommonResult findOrdinaryUser(LoginUsersQO loginUsersQO) {

        List<LoginUsersVO> loginUsersVOList = loginUsersMapper.findOrdinaryUser(loginUsersQO);



        return CommonResult.success(loginUsersVOList);
    }

    @Override
    public CommonResult seleteUser() {

        String userId = JWTUtil.getUserId(request.getHeader("token"));
        LoginUsersVO loginUsersVO = new LoginUsersVO();
        LoginUsers users = loginUsersMapper.selectById(userId);


      return  CommonResult.success(loginUsersVO);
    }

    @Override
    public boolean updateStatus(LoginUsersQO loginUsersQO) {
        int   b =loginUsersMapper.updateStatus(loginUsersQO);

        if (b==1) {
            return  true;
        }
        return  false ;
    }

}

